package BinarySearch;

public class BinarySearchTree {
    public TreeNode root;
     static class TreeNode {

        public int val;

        public TreeNode left;

        public TreeNode right;

        public TreeNode (int val) {
            this.val = val;
        }
    }

    public TreeNode search(int key) {
        TreeNode cur = root;
        while (cur.val != key) {
            if (key > cur.val) {
                cur = cur.right;
            } else {
                cur = cur.left;
            }
            if (cur == null) {
                return null;
            }
        }
        return cur;
    }

    public void insert(int val) {
         TreeNode node = new TreeNode(val);
         if (root == null) {
             root = node;
             return;
         }
         TreeNode cur = root;
         TreeNode parent = null;
         while (cur != null) {
             if (node.val > cur.val) {
                 parent = cur;
                 cur = cur.right;
             }else if (node.val < cur.val) {
                 parent = cur;
                 cur = cur.left;
             } else {
                 return;
             }

         }
         if (parent.val > val) {
             parent.left = node;
         } else{
             parent.right = node;
         }
    }
}
